package com.tct.worktimeboard.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Huhailong
 * @Description 登录拦截器
 * @Date 2021/2/22.
 */
@Slf4j
public class LoginHandler implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(request.getHeader("username"));
        String username = request.getHeader("username");
        if(username != null){
            String userStatus = redisTemplate.opsForValue().get("UserSystem:user:userStatus:" + username);
            if(userStatus != null){
                return true;
            }
        }
        returnJson(response);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    public void returnJson(HttpServletResponse response){
        try(PrintWriter out = response.getWriter()){
            response.setContentType("text/html; charset=utf-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status","notLogin");
            jsonObject.put("message","Place Login!");
            out.write(JSONObject.toJSONString(jsonObject));
        }catch(IOException e){
            log.error(e.getMessage());
        }
    }
}
